<template>
  <div class="editable-cell" :style="{ width: width || '200px' }">
    <div v-if="editable && !disabled" class="editable-cell-input-wrapper">
      <a-input :value="value" @change="handleChange" @pressEnter="check" @blur="check" />
      <a-icon type="check" class="editable-cell-icon-check icon" @click="check" />
      <a-icon type="close" class="editable-cell-icon-close icon" @click="close" />
    </div>
    <div v-else class="editable-cell-text-wrapper">
      <!-- {{ value || placeholder || '请输入' }} -->
      <span v-if="value">{{ value }}</span>
      <span v-else style="color: #bfbfbf">{{ placeholder || '请输入' }}</span>
      <a-icon v-if="!disabled" type="edit" class="editable-cell-icon" :style="editStyle" @click="edit" />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    text: {
      required: true
    },
    placeholder: String,
    width: String,
    editStyle: Object,
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      value: this.text,
      editable: false
    }
  },
  watch: {
    text(val) {
      this.value = val
    }
  },
  methods: {
    handleChange(e) {
      const value = e.target.value
      this.value = value
    },
    check() {
      this.editable = false
      this.$emit('change', this.value)
    },
    close() {
      this.editable = false
    },
    edit() {
      this.editable = true
    }
  }
}
</script>

<style scoped>
.editable-cell {
  position: relative;
  flex-shrink: 0;
  width: 200px;
  margin-left: 10px;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 55px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 28px;
  /* display: none; */
}

.editable-cell-icon-check {
  line-height: 28px;
  position: absolute;
  right: 25px;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon-close {
  line-height: 28px;
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.icon {
  margin-top: 5px;
}
</style>
